package Protocols.Test;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
import java.util.ArrayList;

import Protocols.EnumClientRequests.Login;
import Protocols.EnumClientRequests.Logout;

public class TestServer extends Thread {
	
	private ArrayList<TestClientZuVerwalten> client;
	private ServerSocket serverSocket;
	
	public TestServer(){
		try {
			serverSocket = new ServerSocket(10000);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		client = new ArrayList<TestClientZuVerwalten>(10);
	}
	
	public void run(){
		listenForClients();
	}
	
	public void listenForClients(){
		while (true){
			try {
				System.out.println("Server: Warte auf Client");
				Socket newSocket=serverSocket.accept();
				System.out.println("Server: Mit Client verbunden: "+newSocket.getInetAddress());
				ObjectInputStream newInput = new ObjectInputStream(newSocket.getInputStream());
				ObjectOutputStream newOutput = new ObjectOutputStream(newSocket.getOutputStream());
				Object o=newInput.readObject();
				while (!(o instanceof Login)){
					o=newInput.readObject();
				}
				System.out.println("Server: Login erhalten "+o.toString());
				TestClientZuVerwalten cl = new TestClientZuVerwalten((Login)o, this, newInput, newOutput);
				System.out.println("Server: verwaltbarer Client erzeugt");
				client.add(cl);
				System.out.println("Server: Client starten");
				new Thread(cl).start();
				System.out.println("Server: Client gestartet");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void logout(Logout logout, TestClientZuVerwalten sender){
		System.out.println("Server: es hat sich abgemeldet: "+sender.toString());
		if (client.remove(sender))
			System.out.println("Client aus Liste Entfernt");
		else
			System.out.println("Client konnte nicht aus Liste Entfernt werden");
		System.out.println("Noch auf dem server sind "+client.size()+" Clients");
	}

	public void sendMessage(String s) {
		System.out.println("Message sent by Client: "+s);
		for (TestClientZuVerwalten c: client){
			c.sendMessage(s);
		}
	}

}
